/*
 *@description:家政项目分类页面
 *@Author:@reynold
 *@Date:2025-03-25 17:53:37
 *@Update:2025-03-25 17:53:37
 *@Version: V1.0.0
*/
<template>
  <div class="account_box">
    <!-- 头部返回 -->
    <van-nav-bar title="家政分类" left-text="返回" left-arrow @click-left="onClickLeft" />
    <!-- 产品列表 -->
    <div class="box_product" v-for="item in productList" :key="item.id">
      <van-card :num="item.num" :price="item.price" :desc="item.description" :title="item.name" :thumb="item.imgUrl">
        <template #tags>
          <van-tag plain type="danger">销量{{ item.bookCount }}</van-tag>
          <van-tag plain type="danger">时长{{ item.duration }}</van-tag>
        </template>
        <template #footer>
          <van-button size="mini" icon="plus" round @click="toAddCar(item)"></van-button>
          <van-button size="mini" disabled>{{ item.currentNum }}</van-button>
          <van-button size="mini" icon="minus" round @click="toSubCar(item)"></van-button>
        </template>
      </van-card>
    </div>

    <!-- 购物车 -->
    <van-goods-action>
      <van-goods-action-icon icon="cart-o" text="购物车" :badge="totalcarNum" @click="onClickIcon" />
      <van-goods-action-button type="danger" text="立即购买" @click="onClickButton" />
    </van-goods-action>

    <!-- 弹出面板 -->
    <van-action-sheet v-model="show" title="购物车">
      <div class="content">
        <van-card v-for="item in carFormList" :key="item.id" :num="item.currentNum" :price="item.price" :title="item.name"
          :thumb="item.imgUrl" />
        <van-submit-bar :price="totalPrice" button-text="提交订单" @submit="onSubmit" />
      </div>
    </van-action-sheet>
  </div>
</template>
<script>
import products from './products.js'
import { cloneDeep } from 'lodash'
export default {
  data() {
    return {
      activeKey: 0,
      productList: [
        {
          id: 1,
          name: '产品1',
          num: 100,
          imgUrl: 'https://img.yzcdn.cn/vant-weapp/cat.jpeg',
          price: 100,
          duration: '4小时',
          categoryId: 1,
          rating: '3.5小时',
          bookCount: 800,
          description: '产品描述...包含了什么项目..',
          currentNum: 1
        },
        {
          id: 2,
          name: '产品2',
          num: 100,
          imgUrl: 'https://img.yzcdn.cn/vant-weapp/cat.jpeg',
          price: 100,
          duration: '4小时',
          categoryId: 1,
          rating: '3.5小时',
          bookCount: 800,
          description: '产品描述...包含了什么项目..',
          currentNum: 1
        }
      ],
      carFormList: [],
      totalNum: 0,
      show: false
    }
  },
  computed: {
    // 计算总价
    totalPrice() {
      return this.carFormList.reduce((sum, item) => sum + (item.price * 100 * item.currentNum), 0)
    },
    totalcarNum() {
      return this.carFormList.reduce((sum, item) => sum + item.currentNum, 0)
    }
  },
  methods: {
    // 通过 分类id获取产品
    getProductsById() {
      this.productList = products.list.filter(item => {
        return item.categoryId == this.$route.params.id
      })
    },
    onClickLeft() {
      this.$router.go(-1)
    },
    onChange(index) {
      console.log(index);
    },
    onClickIcon() {
      console.log('icon');
      this.show = true
    },
    onClickButton() {
      console.log('button');
    },

    // 从本地获取购物车数据
    getCarListData() {
      this.carFormList = JSON.parse(localStorage.getItem('carFormList')) || []
    },

    // 将商品添加到数组中
    addCarForm(obj) {
      // 判断当前数组中有没有当前商品
      const existing = this.carFormList.find(item => item.id === obj.id)
      if (existing) {
        existing.currentNum += 1
      } else {
        this.carFormList.push({
          ...cloneDeep(obj),
          currentNum: 1,
          originalStock: obj.num // 保存原始库存
        })
      }
      // 将商品保存到本地存储 进行持久化
      localStorage.setItem('carFormList', JSON.stringify(this.carFormList))
    },
    // 将商品从数组中删除
    delCarForm(obj) {
      const index = this.carFormList.findIndex(item => item.id === obj.id)
      if (index === -1) return

      const target = this.carFormList[index]

      // 更新商品数量
      target.currentNum = Math.max(target.currentNum - 1, 0)

      // 处理数量为0的商品
      if (target.currentNum <= 0) {
        this.carFormList.splice(index, 1)
      } else {
        // 使用 Vue.set 确保响应式更新
        this.$set(this.carFormList, index, {
          ...target,
          num: obj.num // 同步最新库存
        })
      }
      // 将商品保存到本地存储 进行持久化
      localStorage.setItem('carFormList', JSON.stringify(this.carFormList))
    },
    // 将商品添加到购物车
    toAddCar(item) {
      if (item.num <= 0) {
        this.$toast('库存不足')
        return
      }
      // 更新产品列表数量
      item.num--
      item.currentNum++
      this.addCarForm(item)
      this.totalNum = this.carFormList.reduce((sum, c) => sum + c.currentNum, 0)
    },
    // 将商品从购物车中减去
    toSubCar(item) {
      if (item.currentNum <= 0) {
        this.$toast('商品数量不能小于0')
        return
      }

      // 更新产品列表数量
      item.num++
      item.currentNum--
      this.delCarForm(item)
      this.totalNum = this.carFormList.reduce((sum, c) => sum + c.currentNum, 0)
    },

    // 提交订单保存订单数据到本地
    saveOrderList() {
      // 先去查询本地是否有订单数据
      let temporderlist = JSON.parse(localStorage.getItem('mock_orderList')) || []
      let temp = {
          orderId: '订单' + new Date().getTime(),
          name: '订单' + (temporderlist.length + 1),
          createTime: new Date().getTime(),
          resTime: new Date().getTime(), // 预计完成时间
          totolPrice: this.totalPrice,
          status: '待付款',
          produts: this.carFormList
      }
      temporderlist.push(temp)
      // 提交订单
      localStorage.setItem('mock_orderList', JSON.stringify(temporderlist))
      // 清空购物车
      localStorage.removeItem('carFormList')
      this.carFormList = []
    },
    // 提交订单
    onSubmit() {
      console.log('提交订单');
      // 订单在待付款页面查看
      this.saveOrderList()
      this.$notify({
        type: 'success',
        message: '提交订单成功'
      })
      this.show = false
      this.$router.push('/home/order')
    }
  },
  created() {
    this.getProductsById()
    this.getCarListData()
  }
}
</script>
<style scoped>
.box_product {
  margin-bottom: 10px;
}

.content {
  padding: 16px 16px 160px;
}
</style>